package com.wk.code.wkserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wk.code.wkserver.entity.TechType;
import com.wk.code.wkserver.exception.BizException;
import com.wk.code.wkserver.mapper.TechTypeMapper;
import com.wk.code.wkserver.request.admin.TechTypeRequest;
import com.wk.code.wkserver.response.admin.TechTypeResponse;
import com.wk.code.wkserver.response.base.PageInfo;
import com.wk.code.wkserver.service.ITechTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 技术类别表 服务实现类
 * </p>
 *
 * @author wq
 * @since 2021-08-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TechTypeServiceImpl extends ServiceImpl<TechTypeMapper, TechType> implements ITechTypeService {

    @Override
    public void add(TechTypeRequest req) {
        if (StringUtils.isEmpty(req.getName())) {
            throw new RuntimeException("请输入类别名称");
        }
        TechType techType = baseMapper.selectOne(new LambdaQueryWrapper<TechType>().eq(TechType::getName, req.getName()));
        if (Objects.nonNull(techType)) {
            throw new BizException("该类别已经存在");
        }
        TechType demandType = new TechType();
        demandType.setName(req.getName());
        save(demandType);
    }

    @Override
    public void update(TechTypeRequest req) {
        TechType demandType = new TechType();
        BeanUtils.copyProperties(req, demandType);
        updateById(demandType);
    }

    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    @Override
    public TechType detail(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<TechType> page(TechTypeRequest req) {
        LambdaQueryWrapper<TechType> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNoneEmpty(req.getName()), TechType::getName, req.getName());
        wrapper.orderByDesc(TechType::getCreateTime);
        IPage<TechType> typePage = baseMapper.selectPage(req.page(), wrapper);
        return PageInfo.buildPage(typePage);
    }

    @Override
    public List<TechTypeResponse> listPull() {
        return baseMapper.selectList(null).parallelStream().map(x -> {
            TechTypeResponse response = new TechTypeResponse();
            BeanUtils.copyProperties(x, response);
            return response;
        }).collect(Collectors.toList());
    }
}
